<template>
  <div>
    <p>商品清单如下:</p>
    <div v-for="(obj, index) in food" :key="index + ''">
      <span>{{ obj.shopName }}:</span>
      <span>{{ obj.price }}元/份</span>
    </div>
    <p>请选择购买数量:</p>

    <Food
      v-for="(item, index) in food"
      :key="'index_' + index"
      :goodsName="item.shopName"
      :ind="index"
      :count="item.count"
      @add="addFun"
      @sub="subFun"
    ></Food>
    <p>一共购买商品数量:{{ allCount }}</p>
    <p>总价为:{{ allPrice }}</p>
  </div>
</template>

<script>
// 引入组件
import Food from "./components/Food";
export default {
  // 注册组件
  components: {
    Food,
  },
  data() {
    return {
      food: [
        {
          shopName: "可比克薯片",
          price: 5.5,
          count: 0,
        },
        {
          shopName: "草莓酱",
          price: 3.5,
          count: 0,
        },
        {
          shopName: "红烧肉",
          price: 55,
          count: 0,
        },
        {
          shopName: "方便面",
          price: 12,
          count: 0,
        },
      ],
    };
  },
  methods: {
    addFun(ind) {
      this.food[ind].count++;
    },
    subFun(i) {
      this.food[i].count > 0 && this.food[i].count--;
    },
  },
  computed: {
    allCount() {
      return this.food.reduce((sum, obj) => (sum += obj.count * 1), 0);
    },
    allPrice() {
      return this.food.reduce((sum, obj) => (sum += obj.count * obj.price), 0);
    },
  },
};
</script>

<style>
</style>